/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.ubc.icapture.genapha.actions;

/**
 *
 * @author btripp
 */
import ca.ubc.icapture.genapha.beans.Login;
import ca.ubc.icapture.genapha.forms.LoginForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * @version 	1.0
 * @author
 */
public class LoginAction extends Action
{

    @Override
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
    {
        ActionForward forward = mapping.findForward("failure");
        HttpSession session = request.getSession();

        LoginForm loginForm = (LoginForm) form;

        try
        {
            // Login the user.
            Login.loginUser(loginForm.getName(), loginForm.getPassword(), session, response);

            if (Login.getLoggedIn(session))
            {
                try
                {
                    String redir = (String) session.getAttribute("redirUrl");

                    if (redir != null)
                    {
                        // Send the user back to wherever they were before
                        forward = new ActionForward(redir, true);
                    }
                    else
                    {
                        // Something went wrong with the session var
                        // or there were none in the first place.
                        // Return home.
                        forward = mapping.findForward("home");
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    forward = mapping.findForward("home");
                }
            }

            else {
                ActionErrors errors = new ActionErrors();
                errors.add("General",new ActionMessage("errors.invalid.login"));
                saveErrors(request,errors);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        // Finish with
        return forward;
    }
}
